package com.ms.game.log;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import redis.clients.jedis.Jedis;

import com.ms.service.db.jedis.JedisManager;
import com.xpec.c4.db.model.log.basic.BasicLogModel;
import com.xpec.c4.game.utility.GameUtility;
import com.xpec.c4.game.utility.JsonConvert;
import com.xpec.c4.service.module.task.TaskAsyncCommand;

public class GameWriteLogAsyncTask extends TaskAsyncCommand {
	/** log4j object */
	private static final Log log = LogFactory.getLog(GameWriteLogAsyncTask.class);
	
	public static final String REDIS_LOG_LIST_KEY = "LOGS";

	public BasicLogModel gamelog;
	
	@Override
	public void asyncExecute() throws Exception {
		// 用輪詢的方式取得要寫入暫存 log 的 redis
		int logRedisNum = JedisManager.getNextLogRedisNum();

		Jedis jedis = JedisManager.getLogResource(logRedisNum);
		if (jedis == null) {
			if (log.isErrorEnabled()) {
				GameUtility.logErrorException(log, "get log redis resource fail, logRedisNum=" + logRedisNum);
				return;
			}
		}

		// log to json
		String json;
		try {
			json = JsonConvert.toJson(gamelog);
		} catch (Exception e) {
			log.error("object to json fail:" + gamelog.getClass().getSimpleName(), e);
			JedisManager.returnLogResource(logRedisNum, jedis);
			return;
		}
		
		// save
		jedis.rpush(REDIS_LOG_LIST_KEY, json);
		
		JedisManager.returnLogResource(logRedisNum, jedis);
	}

	@Override
	public void execute() throws Exception {
		// TODO Auto-generated method stub

	}

}
